package com.jm.utils.htmlNode;

import java.util.Hashtable;

import org.htmlparser.nodes.RemarkNode;
import org.htmlparser.nodes.TagNode;
import org.htmlparser.nodes.TextNode;

import com.jm.utils.StringHelper;
import com.jm.web.BasePage;


/**
 * @author yanjie
 * Oct 28, 2011 11:00:50 AM
 */
public abstract class XmlNode {
	public abstract void init(Object node,BasePage page);
	public abstract String getNodeName();
	public abstract String getNodeValue();
	
	public abstract Hashtable getAttributes();
	
	public abstract NodeList getChildNodes();
	
	public static XmlNode getInsance(Object object){
		return getInsance(object,null);
	}
	
	public static XmlNode getInsance(Object object,BasePage page){
		 XmlNode node = null;
		 if(object instanceof TextNode){
			TextNode text = (TextNode)object;
			if(!StringHelper.IsNullOrEmpty(text.getText()) &&  StringHelper.getValue(text.getText()).trim().replaceAll("\r","").replaceAll("\n","").length() > 0){
				node = new TxNode();
	         	node.init(text,page);
			}
         }else if(object instanceof TagNode){
        	TagNode tag = (TagNode)object;
        	if(tag != null && !tag.isEndTag()){
        		if("keep".equalsIgnoreCase(tag.getTagName())){
        			node = new TxNode();
        			((TxNode)node).setNodeValue(tag.toHtml().substring(6,tag.toHtml().length()-7));
        		}else if("script".equalsIgnoreCase(tag.getTagName())){
        			node = new TgNode();
        			((TgNode)node).setNodeName(tag.getTagName());
        			((TgNode)node).setNodeValue(tag.toHtml());
        		}else if("select".equalsIgnoreCase(tag.getTagName())){
        			node = new TgNode();
        			((TgNode)node).setNodeName(tag.getTagName());
        			if(tag.getChildren() != null){
        				((TgNode)node).setNodeValue(tag.getChildren().toHtml());
        			}
        			if(tag.getAttributes() != null){
        				((TgNode)node).setAttributes(tag.getAttributes());
        			}
        		}else if(page != null && page.isExportFile() && ( "td".equalsIgnoreCase(tag.getTagName())||"th".equalsIgnoreCase(tag.getTagName()) )){
        			node = new TgNode();
        			((TgNode)node).setNodeValue(tag.toPlainTextString());
        			((TgNode)node).setNodeName(tag.getTagName());
        			if(tag.getAttributes() != null){
        				((TgNode)node).setAttributes(tag.getAttributes());
        			}
        		}else{
	        		node = new TgNode();
	        		node.init(tag,page);
        		}
        	}
         }else if(object instanceof RemarkNode){
        	//node = new ReNode();
        	//node.init((RemarkNode)object);
         }else if(object instanceof org.w3c.dom.Node){
        	node = new W3cNode();
        	node.init((org.w3c.dom.Node)object,page);
         }
         return node;
	}
}
